﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ServiceModel;

namespace GUIL
{
    public partial class BookingGUI : Form, RemoteService.IRemoteServiceCallback
    {
        static RemoteService.IRemoteService _remote;

        RemoteService.Booking _booking;
        readonly RemoteService.Cinema _selectedCinema; // readonly since it should not be changed

        public BookingGUI(RemoteService.Cinema selectedCinema)
        {
            // Hosting client interface ... (more info later)
            // Connection hasn't been opened yet!
            _remote = new RemoteService.RemoteServiceClient(new InstanceContext(this), "WSDualHttpBinding_IRemoteService");

            _selectedCinema = selectedCinema;
            _booking = null;

            InitializeComponent();
        }

        private void BookingGUI_Load(object sender, EventArgs e)
        {
            try
            {
                dataGridViewMovies.DataSource = _remote.GetMoviesUsingCinema(_selectedCinema);
            }
            catch (Exception)
            {
                MessageBox.Show("Failed to get movies.");
            }
        }

        private void dataGridViewMovies_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                // empty current airdates datagrid
                dataGridViewAirtimesMovieHall.RowCount = 0;

                RemoteService.Movie movie = dataGridViewMovies.CurrentRow.DataBoundItem as RemoteService.Movie;
                pictureBox1.ImageLocation = movie.ImgUrl;

                // set new bolded dates
                monthCalendarAirdates.BoldedDates = _remote.GetScreenCasts(dataGridViewMovies.CurrentRow.DataBoundItem as RemoteService.Movie, _selectedCinema).Select(s => s.Airdate).ToArray();
            }
            catch (Exception)
            {
                MessageBox.Show("Failed to get screen casts");
            }
        }

        private void monthCalendarAirdates_DateSelected(object sender, DateRangeEventArgs e)
        {
            try
            {
                // empty current airdates datagrid
                dataGridViewAirtimesMovieHall.RowCount = 0;

                // get new data for grid
                IEnumerable<RemoteService.ScreenCast> _screenCasts = _remote.GetScreenCasts(dataGridViewMovies.CurrentRow.DataBoundItem as RemoteService.Movie, _selectedCinema);
                var _inDateRange = _screenCasts.Where(sc => sc.Airdate >= e.Start && sc.Airdate <= e.End);

                foreach (var item in _inDateRange)
                {
                    // get movie hall object
                    RemoteService.MovieHall _movieHall = _remote.GetMovieHallUsingScreenCast(item);
                    // add new row with data, column 1 is invisible -> used to get selected screencast later
                    dataGridViewAirtimesMovieHall.Rows.Add(
                        item.Id,
                        item.MovieHallId,
                        item.Airdate.ToShortTimeString(),
                        _movieHall.Number,
                        item.Price);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void pickSeats_Click(object sender, EventArgs e)
        {
            // if no airdate is selected, return messagebox, else open movie hall window
            if (dataGridViewAirtimesMovieHall.CurrentRow != null)
            {
                // get selected movie hall by id, movieHallId is saved at second position in datagridview
                int _movieHallId = (int)dataGridViewAirtimesMovieHall.CurrentRow.Cells[1].Value;
                int _screenCastId = (int)dataGridViewAirtimesMovieHall.CurrentRow.Cells[0].Value;
                RemoteService.MovieHall _movieHall = _remote.GetMovieHallUsingId(_movieHallId);
                RemoteService.ScreenCast _screenCast = _remote.GetScreenCast(_screenCastId);
                
                // open seat gui to select seats
                using (var form = new SeatGUI(_movieHall,_screenCast))
                {
                    var result = form.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        _booking = new RemoteService.Booking
                        {
                            PartBookings = form.partBookings,
                            ScreenCast = _screenCast,
                            Creation_date = DateTime.Now
                        }; // Create booking
                        
                        // add movie info to screen cast
                        _booking.ScreenCast.Movie = dataGridViewMovies.CurrentRow.DataBoundItem as RemoteService.Movie;
                        _booking.ScreenCast.MovieHall = _movieHall;

                        ConfirmBooking(); // confirm booking and set user on booking
                    }
                }
            }
            else
            {
                MessageBox.Show("You have to select an air time/movie hall");
            }
        }

        /// <summary>
        /// Open BookingConfirmationGUI and make user enter phoneno.
        /// If booking is canceled, set seats free and open seatGUI again.
        /// </summary>
        private void ConfirmBooking()
        {
            using (var form = new BookingConfirmationGUI(_booking))
            {
                var result = form.ShowDialog();
                if (result == DialogResult.OK)
                {
                    // Booking is saved
                    MessageBox.Show("Booking succeeded");
                }
                else
                {
                    // Open seat gui again.
                    pickSeats_Click(null, null);
                }
            }
        }

        public void OnAction(List<RemoteService.ScreenCast_Seat> screenSeats)
        {
            throw new NotImplementedException();
        }

        private void dataGridViewMovies_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }
    }
}
